package com.csw.android.dev_utils.liveData

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer

/**
 * 可监听观察者改变的MutableLiveData 初始值为null
 *
 * 使用场景：当有观察者时，订阅第三方数据变化，更新到liveData中，当所有观察者都移除时，停止第三方数据监听
 *
 * @property onObserverChanged 观察者发生变化时回调（Boolean:当前是否有观察者[MutableLiveData.hasObservers]）
 */
open class ObserverChangeLiveData<T> : MutableLiveData<T> {
    var onObserverChanged: (ObserverChangeLiveData<T>.(Boolean) -> Unit)? = null

    private var hasObserver = false
        set(value) {
            if (field != value) {
                field = value
                onObserverChanged?.invoke(this, field)
            }
        }

    constructor() : super()

    constructor(value: T?) : super(value)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, observer)
        hasObserver = hasObservers()
    }

    override fun observeForever(observer: Observer<in T>) {
        super.observeForever(observer)
        hasObserver = hasObservers()
    }

    override fun removeObserver(observer: Observer<in T>) {
        super.removeObserver(observer)
        hasObserver = hasObservers()
    }

    override fun removeObservers(owner: LifecycleOwner) {
        super.removeObservers(owner)
        hasObserver = hasObservers()
    }

}